//
//  SRCommentHomeworkViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/10/14.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRCommentHomeworkViewController.h"

#import <NSString+Enhanced.h>
#import <SZTextView.h>
#import "FCUtil.h"
#import "SRPersonalServices.h"
#import "SRSchoolClassServices.h"
#import "AudioRecord.h"
#import "SRAudioPlayerManager.h"
#import "SRUploadQiniuManager.h"
#import "UIButton+FZGreenButton.h"
#import "FZMCCacheManager.h"

@interface SRCommentHomeworkViewController ()<UITextViewDelegate, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet SZTextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *maxCountLabel;
@property (strong, nonatomic) NSString *inputText;
@property (weak, nonatomic) IBOutlet UILabel *helpTipLabel;
@property (strong, nonatomic) UIButton *rightButton;

@property (weak, nonatomic) IBOutlet UIButton *recordButton;

@property (weak, nonatomic) IBOutlet UIView *recordContentView;
@property (weak, nonatomic) IBOutlet UIImageView *recordPlayImageView;
@property (weak, nonatomic) IBOutlet UILabel *recordTimeLabel;

@property (strong, nonatomic) AudioRecord *audioRecord;
//@property (strong, nonatomic) NSString *cafPath;
@property (strong, nonatomic) NSString *mp3Path;
@property (strong, nonatomic) NSString *audioFileName;
@property (strong, nonatomic) NSString *audioKey;

@property (strong, nonatomic) UIActivityIndicatorView *activityView;


@end

@implementation SRCommentHomeworkViewController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		self.minInputTextCount = 0;
		self.maxInputTextCount = 400;
		self.placeholder = @"请点击输入内容";
	}
	
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
		// Do any additional setup after loading the view from its nib.
	
	FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
	
	self.textView.placeholderTextColor = css.color_2;
	self.textView.font = css.fontOfH7;
	self.textView.textColor = css.color_6;
	
	self.title = self.tipTitle;
	self.textView.placeholder = self.placeholder;
	self.helpTipLabel.textColor = css.color_4;
	self.helpTipLabel.font = css.fontOfH5;
	
	if (self.inputText) {
		self.textView.text = self.inputText;
		self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
	} else {
		self.maxCountLabel.text = [NSString stringWithFormat:@"0/%ld", (long)self.maxInputTextCount];
	}
	
	self.textView.delegate = self;
	
	if (self.isFeedback) {
//		self.helpTipLabel.hidden = NO;
		[self setupNavigationBarButtonItem];
	}
	else if (self.isHomeworkComment) {
//		self.helpTipLabel.hidden = YES;
		[self setupNavigationBarButtonItem];
		[self.rightButton setTitle:@"发送点评" forState:UIControlStateNormal];
	}
	else {
		self.helpTipLabel.hidden = YES;
	}
	
	
	[self setupView];
}

- (void)setupView {
	
	FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
	WEAKSELF
	self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	
	[self.recordButton applyGreenBackgroundColor];
	[self.recordButton setTitle:@"按住 说话" forState:UIControlStateNormal];
		//        [self.recordButton addTarget:self action:@selector(onTouchRecordButton:) forControlEvents:UIControlEventAllEvents];
	
	[self.recordButton addEventHandler:^(id sender, UIControlEvents controlEvent) {
		[weakSelf onTouchRecordButton:controlEvent];
		
	} forControlEvents:UIControlEventAllEvents];
	
	self.recordContentView.hidden = YES;
	self.recordContentView.clipsToBounds = YES;
	self.recordContentView.layer.cornerRadius = 4;
	self.recordContentView.backgroundColor = [UIColor colorWithHex:0x10aa14];
	
	
	[self.recordContentView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
			//            if (weakSelf.touchAudioBlock) {
			//                weakSelf.touchAudioBlock();
			//            }
		[weakSelf onUserRecordPlayButton:nil];
	}];
	
//	self.recordPlayImageView = [[UIImageView alloc] init];
//	self.recordTimeLabel = [[UILabel alloc] init];
//	self.recordTimeLabel.textAlignment = NSTextAlignmentLeft;
//
//	self.recordPlayImageView.image = [UIImage imageNamed:@"voice02"];
	self.recordTimeLabel.textColor = [UIColor whiteColor];
	self.recordTimeLabel.font = css.fontOfH6;
	
	
//	self.recordContentView.frame = CGRectMake(0, 0, 120, 44);
//	[self.recordContentView addSubview:self.recordTimeLabel];
//	[self.recordContentView addSubview:self.recordPlayImageView];
//
//	[self.recordPlayImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//		make.leading.equalTo(self.recordContentView).offset(10);
//		make.centerY.equalTo(self.recordContentView);
//		make.width.mas_equalTo(20);
//		make.height.mas_equalTo(26);
//	}];
//
//	[self.recordTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//		make.leading.equalTo(self.recordPlayImageView.mas_trailing).offset(5);
//		make.centerY.equalTo(self.recordPlayImageView);
//		make.height.mas_equalTo(20);
//	}];
	
	self.audioRecord = [[AudioRecord alloc] initFromViewController:self];
	self.audioRecord.completeBlock = ^(BOOL finished, NSURL *audioFilePath) {
		if (finished) {
				//结束录音
	
			NSString *problemID = [NSString stringWithFormat:@"hk%@", weakSelf.showID];
			
			NSString *aacPath = [weakSelf.audioRecord.tmpFileUrl path];
			weakSelf.mp3Path = [FZMCCacheManager recordMp3FilePathWithProblemID:problemID];
			NSError *error = nil;
			[[NSFileManager defaultManager] copyItemAtPath:aacPath toPath:weakSelf.mp3Path error:&error];
			if (error) {
				NSLog(@"file copy error:%@", error);
			}
			
			weakSelf.audioFileName = [weakSelf.mp3Path lastPathComponent];
			
				//            [weakSelf covertCaf:weakSelf.cafPath toMp3:weakSelf.mp3Path];
			
			weakSelf.recordContentView.hidden = NO;
			NSInteger timeStamp = [weakSelf.audioRecord timeLenght];
			if (timeStamp <= 60) {
				weakSelf.recordTimeLabel.text = [NSString stringWithFormat:@"%02ld秒", (long)timeStamp];
			} else {
				weakSelf.recordTimeLabel.text = [NSString stringWithFormat:@"%02ld分%02ld秒", timeStamp / 60, timeStamp % 60];
			}
//			[weakSelf.tableView addSubview:weakSelf.recordContentView];
//			weakSelf.recordContentView.frame = CGRectMake(SCREEN_WIDTH - 220, weakSelf.headerHeight + 30, 200, 44);
			
			[weakSelf convertMp3Success];
				//            weakSelf.recordButton.hidden = YES;
			
		} else {
				//时间太短，提示
			[weakSelf.audioRecord showTooShortSign];
		}
	};
	
	SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
	[audioPlayer setAudioFilePath:nil];
	[audioPlayer setAudioFileName:nil];
	
	audioPlayer.audioPlayerCompletedBlock = ^(BOOL finish) {
			//		[weakSelf.headerView setActivityAnimated:NO];
		[weakSelf.activityView stopAnimating];
	};
	
	audioPlayer.audioPlayerProgressBlock = ^(CGFloat progress) {
		if (progress > 0.2) {
				//                [weakSelf.activityView stopAnimating];
		}
		
	};
	
	audioPlayer.audioRecorderFailureBlock = ^(NSString *message) {
		[weakSelf showHUDErrorMessage:message];
	};
	
	[self.view addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
		[weakSelf hideKeyboard];
		
	}];
}

- (void)hideKeyboard {
	[self.textView resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
		//    [self.textView becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	
	[[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
	
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
		// Dispose of any resources that can be recreated.
}

- (void)setupNavigationBarButtonItem {
	FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
	UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
	[rightButton setTitle:@"提交" forState:UIControlStateNormal];
	rightButton.titleLabel.font = css.fontOfH4;
	[rightButton setTitleColor:css.color_4 forState:UIControlStateNormal];
	
	[rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
	rightButton.frame = CGRectMake(0, 0, 80, 44);
	[rightButton addTarget: self action: @selector(onSubmitButton:) forControlEvents: UIControlEventTouchUpInside];
	self.rightButton = rightButton;
	
	UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
	[self setRightBarButtonItem:rightBarItem];
}


#pragma mark - Event

- (void)onSubmitButton:(id)sender {
	WEAKSELF
	[self.textView resignFirstResponder];
	if ([self.inputText length] <= self.minInputTextCount) {
		[self showHUDHintWithText:@"请输入内容"];
		return;
	}
	if (self.isHomeworkComment) {
			//发送点评
		NSMutableDictionary *params = [NSMutableDictionary dictionary];
		[params setValue:self.showID forKey:@"show_id"];
		[params setValue:self.inputText forKey:@"comment"];
		[params setValue:@(self.homeworkType) forKey:@"ctype"];
		[params setValue:self.problem_finish_id forKey:@"problem_finish_id"];
		
		if (self.audioFileName) {
			[params setValue:self.audioFileName forKey:@"comment_audio"];
			[params setValue:@([self.audioRecord timeLenght]) forKey:@"comment_audio_timelen"];
		}
		
		[SRSchoolClassServices addHomeworkCommentWithParams:params successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
			if (statusCode == kFZRequestStatusCodeSuccess) {
				[weakSelf showHUDHintWithText:@"发送成功"];
				if (weakSelf.didSendBlock) {
					weakSelf.didSendBlock(weakSelf.inputText);
				}
				
				[weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:2];
			} else {
				[weakSelf showHUDHintWithText:message];
			}
		} failureBlock:^(id responseObject, NSError *error) {
			[weakSelf showHUDError];
			
		}];
		return;
	}
	
	
	[weakSelf startProgressHUD];
	[SRPersonalServices sendFeedbackWithContent:self.inputText successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
		[weakSelf stopProgressHUD];
		if (statusCode == kFZRequestStatusCodeSuccess) {
			[weakSelf showHUDHintWithText:@"反馈成功"];
			
			[weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:3];
		} else {
			[weakSelf showHUDHintWithText:message];
		}
		
	} failureBlock:^(id responseObject, NSError *error) {
		[weakSelf showHUDError];
	}];
}

- (void)setPreText:(NSString *)preText {
	_preText = preText;
	
	self.inputText = preText;
}

- (void)doBack {
	
	[[SRAudioPlayerManager sharedInstance] setAudioFileName:nil];
	
	if ([self.inputText length] > 0 && [self.inputText length] < self.minInputTextCount){
			//若小于10 则提示
		WEAKSELF
		NSString *message = [NSString stringWithFormat:@"%@至少输入%d个字", self.tipTitle, (int)self.minInputTextCount];
		
		UIAlertView *alertView = [UIAlertView alertViewWithTitle:nil message:message cancelButtonTitle:@"继续编辑" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
			if (buttonIndex == 0) {
					//退出
				weakSelf.inputText = nil;
				if (weakSelf.didChangeInputTextBlock) {
					weakSelf.didChangeInputTextBlock(self.inputText);
				}
				[weakSelf.navigationController popViewControllerAnimated:YES];
			}
		} otherButtonTitles:@"退出", nil];
		
		[alertView show];
		
			//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
			//        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"继续编辑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			//
			//        }];
			//
			//        UIAlertAction *exitAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			//            [weakSelf.navigationController popViewControllerAnimated:YES];
			//        }];
			//
			//        [alertController addAction:alertAction];
			//        [alertController addAction:exitAction];
			//
			//        [self presentViewController:alertController animated:YES completion:nil];
	} else {
		[super doBack];
	}
}

- (void)onUserRecordPlayButton:(id)sender {
	SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
	
//	if (self.isFinishedDetail) {
//		NSString *url = self.currentItemModel.answerByUser;
//
//		if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
//			if (audioPlayer.isPlaying) {
//				[self.activityView stopAnimating];
//				[audioPlayer pauseRecordAudio];
//			} else {
//				[self.activityView startAnimating];
//				audioPlayer.audioFilePath = nil;
//				[[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
//				[[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
//
//			}
//		}
//		else {
//			[self.activityView startAnimating];
//			audioPlayer.audioFilePath = nil;
//
//			[[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
//			[[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
//
//		}
//	} else {
		NSString *url = self.mp3Path;
		
		if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
			if (audioPlayer.isPlaying) {
//				[self.activityView stopAnimating];
				[audioPlayer pauseRecordAudio];
			} else {
//				[self.activityView startAnimating];
				[audioPlayer startPlayRecordAudio];
			}
		}
		else {
//			[self.activityView startAnimating];
			[[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:url];
			[[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
			
		}
//	}
}

- (void)onTouchRecordButton:(UIControlEvents)touchEvent {
//	[self.activityView stopAnimating];
//	[self.headerView setActivityAnimated:NO];
	[[SRAudioPlayerManager sharedInstance] pauseRecordAudio];
	
	if (UIControlEventTouchDown == touchEvent) {
		[self.audioRecord recordBegin];
	} else if (UIControlEventTouchDragInside == touchEvent ||
			   UIControlEventTouchDragEnter == touchEvent) {
		self.audioRecord.voiceRecordView.state = LCChatRecorderMetersAlertViewStateRecording;
	} else if (UIControlEventTouchDragOutside == touchEvent ||
			   UIControlEventTouchDragExit == touchEvent) {
		[self.audioRecord removeMicIconAndAddDeleteIcon];
	} else if (UIControlEventTouchUpInside == touchEvent) {
		[self.audioRecord recordComplete];
	} else if (UIControlEventTouchUpOutside == touchEvent ||
			   UIControlEventTouchCancel == touchEvent) {
		[self.audioRecord recordCancel];
	}
	
}

- (void)convertMp3Success {
	[self stopProgressHUD];
		//开始上传进度条
	[self updateHUDgrogress:MBProgressHUDModeDeterminate labelText:@"上传录音..."];
	WEAKSELF
		//上传图片到七牛云端
//	self.audioKey = [NSString stringWithFormat:@"showComment_%lld.aac", (long long)[[NSDate date] timeIntervalSince1970]];
	
	[[SRUploadQiniuManager sharedInstance] uploadFileToQiNiuForPath:self.mp3Path key:self.audioFileName uploadToken:[SRLoginUser uploadToken] UploadPercent:^(NSString *key, float percent) {
		CGFloat progress = MIN(percent, 1.0);
		[weakSelf updateMyProgressTask:progress];
		
	} responseBlock:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
		[weakSelf stopProgressHUD];
		
		if (info.isOK) {
				//上传成功
//			weakSelf.currentItemModel.answerByUser = key;
			
		} else {
				//上传数据失败
			[weakSelf.recordButton setHidden:NO];
			
			NSString *message = [NSString stringWithFormat:@"录音上传失败ErrorCode(%d):%@", info.statusCode, resp];
			
			if (info.statusCode == 401) {
					//token失效过期，提示重新登录
				message = [NSString stringWithFormat:@"认证过期，请重新登录\n录音上传失败ErrorCode(%d):%@", info.statusCode, resp];
				[weakSelf showHUDErrorMessage:message];
				
				[weakSelf performSelector:@selector(showLoginViewController) withObject:nil afterDelay:1];
				
			} else {
				[weakSelf showHUDErrorMessage:message];
				
			}
		}
	}];
}

- (void)showLoginViewController {
	[[SRLoginManager sharedManager] logout];
	[[SRLoginManager sharedManager] showLoginViewSinceController:self];
}


#pragma mark - UITextViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	[self.textView resignFirstResponder];
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
	
}
- (void)textViewDidEndEditing:(UITextView *)textView {
		//    NSLog(@"textViewDidEndEditing:%@", textView.text);
	
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
	NSString * originText = textView.text;
	if (([originText length] + [text length]) > self.maxInputTextCount) {
		NSString *message = [NSString stringWithFormat:@"最多输入%ld个字", (long)self.maxInputTextCount];
		[self showHUDHintWithText:message];
		return NO;
	}
	return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
		//    NSLog(@"textViewDidChange:%@", textView.text);
	self.inputText = [textView.text stringToTrimWhiteSpace];
	
	if ([self.inputText length] > self.maxInputTextCount) {
		NSInteger maxLength = self.maxInputTextCount * 2;
		NSArray *lengths = [FCUtil stringLengthWithString:self.inputText maxLength:maxLength];
		if([lengths count] > 0 && [[lengths objectAtIndex:0] integerValue] > maxLength){
			NSString * text = [self.inputText substringToIndex:[[lengths objectAtIndex:1] integerValue]];
			if([NSThread isMainThread]){
				self.textView.text = text;
				self.inputText = text;
				self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
				
				if (self.didChangeInputTextBlock) {
					self.didChangeInputTextBlock(self.inputText);
				}
			}else{
				dispatch_async(dispatch_get_main_queue(), ^{
					self.textView.text = text;
					self.inputText = text;
					self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
					
					if (self.didChangeInputTextBlock) {
						self.didChangeInputTextBlock(self.inputText);
					}
				});
			}
			
			NSString *message = [NSString stringWithFormat:@"最多输入%ld个字", (long)self.maxInputTextCount];
			[self showHUDHintWithText:message];
		}
	} else {
		self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
		
		if (self.didChangeInputTextBlock) {
			self.didChangeInputTextBlock(self.inputText);
		}
	}
}

@end
